<?php
declare (strict_types=1);
namespace App\Model;

use Hyperf\DbConnection\Db;
use Hyperf\DbConnection\Model\Model;
/**
 * @property int $id 
 * @property int $appid 
 * @property string $account 
 * @property string $account_fid
 * @property int $created_at
 * @property int $updated_at
 */
class Friend extends BaseModel
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'friend';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = ['id' => 'integer', 'appid' => 'integer', 'created_at' => 'integer', 'updated_at' => 'integer'];

    /**
     * 不管理 created_at 和 updated_at
     * @var bool
     */
    public $timestamps = false;

    /**
     * 添加好友
     * @param $appid
     * @param $array
     * @return string
     */
    public static function add($appid,$array): string
    {
        $time = time();
        $account = $array['account'] ?? '';
        $account_fid = $array['account_fid'] ?? '';

        if (empty($account))
            return 'account is null';

        if (empty($account_fid))
            return 'account_fid is null';

        if ($account == $account_fid)
            return '不能添加自己';

        $where = [
            'appid'      => $appid,
            'account'    => $account,
            'account_fid'=> $account_fid
        ];

        $res_int = 0;
        $info = self::where($where)->first('status');
        if ($info){
            if ($info->status == 0)
                return '已提交过申请';

            if ($info->status == 1)
                return '当前已为好友';

            if ($info->status == 2)
                return '已被拉黑';

            if ($info->status == 3) // 删除
            {
                $res_int = self::where($where)->update(['status'=>0,'created_at'=>$time]);
            }

        }else{
            $data = [
                'appid'      => $appid,
                'account'    => $account,
                'account_fid'=> $account_fid,
                'created_at' => $time,
            ];

            $res_int = self::insertGetId($data);
        }

        if ($res_int > 0)
            return '';

        return '添加失败';
    }

    /**
     * 同意申请
     * @param $appid
     * @param $array
     * @return string
     */
    public static function agree($appid,$array)
    {
        $time = time();
        $account = $array['account'] ?? '';
        $account_fid = $array['account_fid'] ?? '';

        if (empty($account))
            return 'account is null';

        if (empty($account_fid))
            return 'account_fid is null';

        $where = [
            'appid'      => $appid,
            'account'    => $account_fid,
            'account_fid'=> $account
        ];

        $info = self::where($where)->first('status');
        if ($info)
        {
            if ($info->status == 2)
                return '已被拉黑';
            if ($info->status == 1)
                return '已为好友';
            if ($info->status == 3)
                return '已删除';

            Db::beginTransaction();
            try {
                self::where($where)->update(['status'=>1,'updated_at'=>$time]);

                $where_friend = [
                    'appid' => $appid,
                    'account' => $account,
                    'account_fid' => $account_fid,
                ];
                $friend_data = $where_friend;
                $friend_data['status'] = 1;
                $friend_data['created_at'] = $time;
                $friend_data['updated_at'] = $time;
                self::where($where_friend)->updateOrInsert($friend_data);

                Db::commit();

                return '';
            }catch (\Exception $e){
                Db::rollBack();
                return '同意失败 ' . $e->getMessage();
            }

        }else{
            return '没有申请邀请';
        }
    }

    /**
     * @param $appid
     * @param $account
     * @param $account_fid
     * @return string
     */
    public static function del($appid, $account, $account_fid): string
    {
        $where = [
            'appid' => $appid,
            'account' => $account,
            'account_fid' => $account_fid,
        ];

        $res_int = self::query()->where($where)->delete();
        if ($res_int > 0){
            return '';
        }
        return '删除好友失败或不存在的好友';
    }

    /**
     * 获取好友列表
     * @param $appid
     * @param $array
     * @return array|string
     */
    public static function getList($appid, $array)
    {
        $page    = $array['page'] ?? 1;
        $p_size  = $array['p_size'] ?? self::$_p_size;
        $account = $array['account'] ?? '';
        $keyword = $array['keyword'] ?? '';
        $status  = $array['status'] ?? -1;

        if (empty($account))
            return 'account is null';

        $where = [
            'appid'   => $appid,
            'account' => $account
        ];
        if (!empty($keyword))
        {
            $where['account_fid'] = ['like'=>'%'.$keyword];
        }

        if (intval($status) > -1)
        {
            $where['status'] = $status;
        }

        $data = self::select(['account_fid','status'])
            ->where($where)
            ->orderByDesc('id')
            ->offset(self::p_offset($page,$p_size))
            ->limit(self::p_size($p_size))
            ->get()
            ->toArray();

        foreach ($data as &$val)
        {
            $val['status'] = self::refStatus($val['status']);
        }

        return $data;
    }

    /**
     * 获取单个好友的信息
     * @param $appid
     * @param $array
     * @return array|string
     */
    public static function getOne($appid, $array)
    {
        $account     = $array['account'] ?? '';
        $account_fid = $array['account_fid'] ?? '';

        if (empty($account))
            return 'account is null';

        if (empty($account_fid))
            return 'account_fid is null';

        $where = [
            'appid' => $appid,
            'account' => $account,
            'account_fid' => $account_fid,
            'status' => 1, // 同意好友
        ];
        $data = self::where($where)
            ->select(['account','account_fid'])
            ->first();
        if ($data)
        {
            $data = $data->toArray();

            $user = UserBind::where(['account'=>$data['account_fid']])->first(['username','avatar']);
            if ($user)
            {
                $user = $user->toArray();
                $data = array_merge($data,$user);
            }
            $data['account'] = $data['account_fid'];
            unset($data['account_fid']);

            return $data;
        }
        return '当前不是好友';

    }

    /**
     *
     * @param $appid
     * @param $array
     * @return string|string[]
     */
    public static function delFried($appid, $array)
    {
        $account     = $array['account'] ?? '';
        $account_fid = $array['account_fid'] ?? '';
        $type        = $array['type'] ?? 'single';

        $type_arr = [
            'single', // 单向删除
            'both',   // 双向删除
        ];
        if (!in_array($type, $type_arr))
            return 'type error';

        if (empty($account))
            return 'account is null';

        if (empty($account_fid))
            return 'account_fid is null';

        if ($account_fid == $account)
            return '不能删除自己';

        $where = ['appid'=>$appid,'account'=>$account,'account_fid'=>$account_fid];

        $info = self::where($where)->first(['status']);
        if (!$info)
            return '当前已不是好友';

        $where_fid = ['appid'=>$appid,'account'=>$account_fid,'account_fid'=>$account];
        Db::beginTransaction();
        try {

            switch ($type)
            {
                case 'single':
                    self::where($where)->delete();
                    self::where($where_fid)
                        ->update(['status'=>2]);
                    break;
                case 'both':
                    self::where($where)->delete();
                    self::where($where_fid)->delete();
                    break;
            }

            Db::commit();

            return [
                'del_account'=>$account_fid,
                'type' => $type
            ];
        }catch (\Exception $exception)
        {
            Db::rollBack();
            return $exception->getMessage();
        }

    }


    private static function refStatus($status)
    {
        switch ($status)
        {
            case 0:
                $status = '申请中';
                break;
            case 1:
                $status = '同意';
                break;
            case 2:
                $status = '拉黑';
                break;
            case 3:
                $status = '已删除';
                break;
            default:
                $status = '未知';
                break;
        }
        return $status;
    }




}